package com.example.demo.Util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
@Component
public class JWTUtil {
    private static final long EXPIRATION = 30*60 * 1000;
    @Value("${jwt.issuer}")
    public void setIss(String iss) {
        ISS = iss;
    }
    private static String ISS ;

    /**
     * 根据userid生成jwt令牌
     * @param
     * @return
     */
    public static String createJWT(Object userId){
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("userId",userId);
        String jwt = Jwts.builder().signWith(SignatureAlgorithm.HS256, ISS)
                .addClaims(objectObjectHashMap)
                .setExpiration(new Date(System.currentTimeMillis() +EXPIRATION)) //有效期60s
                .compact();
        return jwt;
    }
public static Claims parseJWT(String jwt){
    Claims claims = Jwts.parser().setSigningKey(ISS).parseClaimsJws(jwt).getBody();
    return claims;
}
}
